var express = require('express');
const md5 = require('md5');



var UserModel = require('../../models/UserModel');
var router = express.Router();

router.get('/reg', (req, res) => {
    //响应html内容
    res.render('auth/reg');
})


router.post('/reg', (req, res) => {
    //获取请求体数据
    console.log(req.body);
    UserModel.create({ ...req.body, password: md5(req.body.password) })
        .then(() => {
            res.render('success', { msg: '注册成功', url: '/login' })
        })
        .catch((err) => {
            res.status(500).send('注册失败')
        })
})

/**
 * 登录页面
 */
router.get('/login', (req, res) => {
    //响应html内容
    res.render('auth/login');
})


router.post('/login', (req, res) => {
    let { username, password } = req.body;
    UserModel.findOne({ username: username, password: md5(password) })
        .then((data) => {
            req.session.username = data.username;
            req.session._id = data._id;
            res.render('success', { msg: '登录成功', url: '/account' }) 
        })
        .catch(() => { res.status(500).send('登陆失败,账号或密码错误') })
})


router.post('/logout', (req, res) => {
    req.session.destroy(()=>{
        res.render('success',{msg:'退出成功',url:'/login'})
    });
})

module.exports = router;
